class LinksController < ApplicationController

  attr_reader :query

  #
  # TA note:
  # 'like' search performs approximately boolean search using the 'like' SQL 
  # construct. It is slow and does not rank results in a relevant order. 
  #
  # There is non-trivial Ruby string manipulation going on here. If you
  # are curious, start here:
  # http://www.ruby-doc.org/core/classes/String.html
  #
  def nsearch
    @query = params[:query]
    if !@query.to_s.strip.empty?      
      tokens = @query.split.collect {|c| "%#{c.downcase}%"}
      predicates = (["(lower(links.body) like ? or lower(links.e_from) like ? or lower(links.e_to) like ?)"] * tokens.size).join(" and ") 
      conditions = ["#{predicates}", * (tokens * 3).sort]
      @all_results = Link.find :all, :conditions => conditions
      build_graph(@all_results)
    end
  end
  
  #
  # TA note:
  # below is mostly boiler-plate RoR code
  # we did add in pagination of results
  #

  # GET /links
  # GET /links.xml
  def index
    @links = Link.paginate :page => params[:page]
    
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @links }
    end
  end

  # GET /links/1
  # GET /links/1.xml
  def show
    @link = Link.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @link }
    end
  end

  # GET /links/new
  # GET /links/new.xml
  def new
    @link = Link.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @link }
    end
  end

  # GET /links/1/edit
  def edit
    @link = Link.find(params[:id])
  end

  # POST /links
  # POST /links.xml
  def create
    @link = Link.new(params[:link])

    respond_to do |format|
      if @link.save
        flash[:notice] = 'Link was successfully created.'
        format.html { redirect_to(@link) }
        format.xml  { render :xml => @link, :status => :created, :location => @link }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @link.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /links/1
  # PUT /links/1.xml
  def update
    @link = Link.find(params[:id])

    respond_to do |format|
      if @link.update_attributes(params[:link])
        flash[:notice] = 'Link was successfully updated.'
        format.html { redirect_to(@link) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @link.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /links/1
  # DELETE /links/1.xml
  def destroy
    @link = Link.find(params[:id])
    @link.destroy

    respond_to do |format|
      format.html { redirect_to(links_url) }
      format.xml  { head :ok }
    end
  end
end
